package leetCode.hw.math;

import java.util.Stack;

public class HJ50Solution implements HJ50 {

    /**
     * 四则运算
     * @param str
     * @return
     */
    @Override
    public double cal(String str) {
        str = str.replaceAll("[{,\\[]","(");
        str = str.replaceAll("[},\\]]",")");
        int n = str.length();
        // res1为已经计算好的部分值,res2为正在计算的值
        // 初始化
        double res1 = 0, res2 = 1;
        // add==1(+) add==-1(-)
        // mul==1(*) mul==-1(/)
        double mul = 1, add = 1;
        Stack<Double> stack = new Stack<>();
        for(int i=0;i<n;i++) {
            char c = str.charAt(i);
            //如果是乘除符号,存储到o2中
            if(c=='*'||c=='/') {
                mul = c=='*'?1:-1;
            }
            // 如果遇到数字,读取数字存入num2中
            else if(Character.isDigit(c)) {
                int cur = 0;
                while(i<n&&Character.isDigit(str.charAt(i))){
                    cur = cur * 10 + (str.charAt(i)-'0');
                    i++;
                }
                i--;
                res2 = mul==1?res2*cur:res2/cur;
            }
            // 遇到加减
            else if(c == '+' || c=='-') {
                // 如果减号出现在计算式的开始
                if(c=='-'&&(i==0||str.charAt(i-1)=='('||str.charAt(i-1)=='*'||str.charAt(i-1)=='/')) {
                    add = -1;
                    continue;
                }
                res1 = res1 + add * res2;
                add  = (c=='+'?1:-1);
                res2 = 1;
                mul = 1;
            }
            // 如果左括号，需要把前面计算的数据存起来
            else if(c=='(') {
                stack.push(res1);
                stack.push(add);
                stack.push(res2);
                stack.push(mul);
                res1 = 0;
                add = 1;
                res2 = 1;
                mul = 1;
            }
            // 遇到右括号
            else {
                double cur = res1 + add * res2;
                mul = stack.pop();
                res2 = stack.pop();
                add = stack.pop();
                res1 = stack.pop();
                res2 = mul == 1?res2*cur:res2/cur;
            }
        }
        return res1+add*res2;
    }



    public static void main(String[] args) {
        System.out.println((int)new HJ50Solution().cal("3+2*{1+2*[-4/(8-6)+7]}"));
    }

}
